package zy.testsqlite.Database;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;

/**
 * Created by Administrator on 2017/7/3.
 */

public class DatabaseHelper extends SQLiteOpenHelper {
    public static final String CREATE_BOOK = "create table Book(" +
            //primary key 将id列设为主键    autoincrement表示id列是自增长的
            "id integer primary key autoincrement," +
            "author text," +
            "price real," +
            "name text);";

    public static final String CREATE_GROUPS= "create table groups(" +
            "id varchar(20),"+
            "primary key(id));";

    public static final String CREATE_USER= "create table user(" +
            "id integer,"+
            "name varchar(20),"+
            "groupId varchar(20),"+
            "primary key(id),"+
            "foreign key (groupId) references  groups(id)  on delete cascade on update cascade);";

    private Context mContext;
    //构造方法：第一个参数Context，第二个参数数据库名，第三个参数cursor允许我们在查询数据的时候返回一个自定义的光标位置，一般传入的都是null，第四个参数表示目前库的版本号（用于对库进行升级）
    public DatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory , int version){
        super(context,name ,factory,version);
        mContext = context;
    }
    @Override
    public void onOpen(SQLiteDatabase db) {
        super.onOpen(db);
        if(!db.isReadOnly()) { // Enable foreign key constraints
            db.execSQL("PRAGMA foreign_keys=ON;");
        }
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        //调用SQLiteDatabase中的execSQL（）执行建表语句。
        try {
            db.execSQL(CREATE_BOOK);
            db.execSQL(CREATE_GROUPS);
            db.execSQL(CREATE_USER);
            //db.execSQL("");
            Toast.makeText(mContext, "Create succeeded", Toast.LENGTH_SHORT).show();
        }catch (Exception e){
            Toast.makeText(mContext, "Create fail", Toast.LENGTH_SHORT).show();
        }
        //创建成功

    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    public void onUpgrade1(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}
